%%%-------------------------------------------------------------------
%% @doc metronome_test public API
%% @end
%%%-------------------------------------------------------------------

-module(metronome_test).

-include_lib("eunit/include/eunit.hrl").

-export([run/0]).

run() ->
    ?debugMsg("metronome test begin."),
    metronome:start(),

    Fun1 = fun() ->
        erlang:put(intensity, erlang:system_time(millisecond)),
        loop()
    end,
    Pid = spawn_link(Fun1),

    ?debugMsg("metronome process duplicate join."),
    metronome:join(Pid),
    metronome:join(Pid),
    timer:sleep(2000),

    ?debugMsg("metronome process rejoin."),
    metronome:quit(Pid),
    metronome:join(Pid),
    timer:sleep(2000),

    ?debugMsg("metronome 1000 process test."),
    TimeStamp = erlang:system_time(millisecond) + 5000,
    Fun2 = fun() ->
        loop(TimeStamp + rand:uniform(2000))
    end,
    [metronome:join(spawn_link(Fun2)) || _Dummy <- lists:duplicate(1000, dummy)],
    timer:sleep(8000),


    Pid ! stop,
    timer:sleep(1000),

    metronome:stop(),

    ?debugMsg("metronome test end."),

    ok.

%% internal functions
loop() ->
    receive
        stop ->
            ?debugMsg("metronome test process stop.");
        Msg ->
            Timer = erlang:system_time(millisecond),
            Intensity = Timer - erlang:put(intensity, Timer),
            ?debugFmt("metronome process Msg:~p, Intensity millisecond:~p.", [Msg, Intensity]),
            loop()
    after
        10000 ->
            exit(timeout)
    end.

loop(ExitTimer) ->
    receive
        stop ->
            ok;
        _Msg ->
            CurrentTimer = erlang:system_time(millisecond),
            if
                CurrentTimer > ExitTimer -> ok;
                true -> loop(ExitTimer)
            end
    after
        10000 ->
            exit(timeout)
    end.